﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;

namespace OutlookTags.Helpers
{
    internal static class TextFormatHelper
    {
        public static string ConvertTagsToRtf(string rawTagString, Dictionary<string, DisplayTag> tagsHash)
        {
            var separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            Func<string, bool> Contains = tag => tagsHash.ContainsKey(tag.Trim().ToUpper());
            string[] tagCollection = rawTagString.Split(';', ',');
            StringBuilder tagRtf = new StringBuilder();
            tagRtf.Append(@"{\rtf1\ansi\ansicpg1251\deff0\deflang1049{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\*\generator Riched20 12.0.6413.1000;}\viewkind4\uc1\pard\f0\fs18 ");

            Regex replacer = new Regex(@"^(?<a1>\s*)(?<a2>\w+(\s*\w+)*)(?<a3>\s*)$");

            if (tagCollection.Length > 0)
            {
                FormatSingleTag(tagCollection[0], tagRtf, replacer, Contains);
                
                for (int i = 1; i < tagCollection.Length; i++)
                {
                    tagRtf.Append(separator);
                    FormatSingleTag(tagCollection[i], tagRtf, replacer, Contains);
                }
            }
         
            tagRtf.Append("}");

            return tagRtf.ToString();
        }

        public static string GetCurrentTagPrefix(string text)
        {
            string[] tags = text.Split(',', ';');
            return tags[tags.Length - 1];
        }

        private static void FormatSingleTag(string tag, StringBuilder tagRtf, Regex replacer, Func<string, bool> Contains)
        {            
            string tempTag = tag.Trim();
            tag = tag.Replace(@"\", @"\\");
            if (tempTag.Length == 0 || !Contains(tempTag))
            {
                tagRtf.Append("{");
                tagRtf.Append(tag);
                tagRtf.Append("}");
            }
            else
                tagRtf.Append(replacer.Replace(tag, @"{${a1}}{\ul ${a2}}{${a3}}"));
        }

        public static string ReplaceLast(string source, string completeText)
        {
            var separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;            
            string[] tagCollection = source.Split(';', ',');
            StringBuilder result = new StringBuilder();

            for (int i = 0; i < tagCollection.Length - 1; i++)
            {
                result.Append(tagCollection[i]);
                result.Append(separator);
            }

            result.Append(completeText);

            return result.ToString();
        }
    }
}
